<!-- 我的合同 -->
<!-- 用户管理 -->
<template>
    <div class="app-container" style="width:1650px">
      <el-row :gutter="20">
       
        <el-col :span="20" :xs="24">
          <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" >
            <el-form-item label="用户名称" prop="realName" >
              <el-input
                v-model="queryParams.realName"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="userPhone">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="用户状态"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button type="danger" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form> -->
  
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
          
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
               
                
              >导入</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                
                
              >导出</el-button>
            </el-col> -->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>
  
          <el-table v-loading="loading" :data="contractList" tooltip-effect="dark" @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="20" align="center"  />
            <el-table-column label="编号" align="center" key="id" prop="id" v-if="columns[0].visible" width="70px"/>
            <el-table-column label="用户id" align="center" key="userId" prop="userId" v-if="columns[1].visible" width="100px"/>
            <el-table-column label="订单id" align="center" key="orderId" prop="orderId" v-if="columns[1].visible" width="100px"/>

            <el-table-column label="合同编号" align="center" key="contractNumber" prop="contractNumber" v-if="columns[2].visible" width="100px" show-overflow-tooltip/>

            <el-table-column label="合同名称" align="center" key="contractName" prop="contractName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
            
            <el-table-column label="发起人" align="center" key="initiator" prop="initiator" v-if="columns[4].visible" :show-overflow-tooltip="true" />
            <el-table-column label="发起人电话" align="center" key="initiatorPhone" prop="initiatorPhone" v-if="columns[5].visible" :show-overflow-tooltip="true" width="100px"/>
            <el-table-column label="合同来源" align="center" key="contractSource" prop="contractSource" v-if="columns[7].visible" :show-overflow-tooltip="true" />

            <el-table-column label="签署状态" align="center" key="contractStatus" v-if="columns[8].visible">
              <template slot-scope="scope">
              <span v-if="scope.row.contractStatus == 0" style="color:brown">未签署</span>
              <span v-if="scope.row.contractStatus == 1" style="color:aqua">已签署</span>
              </template>
            </el-table-column>  
            <!-- <el-table-column label="签署状态" align="center" key="contractStatus" v-if="columns[8].visible">
              <template slot-scope="scope"  >
            {{
              scope.row.contractStatus == 0
                ? "未签署" 
                : scope.row.contractStatus == 1
                ? "已签署"
                : scope.row.contractStatus == 2
                ? "审核中"
                : ""
            }}</template
          >
            </el-table-column>  -->
           <el-table-column label="完成时间" align="center" prop="completionTime" v-if="columns[6].visible" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.completionTime) }}</span>
              </template>
            </el-table-column> 
            <!-- <el-table-column label="修改时间" align="center" prop="updateTime" v-if="columns[9].visible" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>  -->
            <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope" >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)" v-if="scope.row.contractStatus == 0" aria-disabled="true"
                  
                >签署合同</el-button>
              

                <el-button type="text" @click="dialogVisible = true" v-if="scope.row.contractStatus == 1" aria-disabled="true">还款信息表 </el-button>
                

            
              </template>
            </el-table-column>
          </el-table>
  
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>

  <!-- 还款信息表2 -->
      <el-dialog title="还款信息表" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" align="center" >
        
        <el-table v-loading="loading" :data="contractList"  >
          <el-table-column label="合同编号" align="center" key="contractNumber" prop="contractNumber"  />
          <el-table-column label="合同名称" align="center" key="contractName" prop="contractName"  />
          <el-table-column label="发起人" align="center" key="initiator" prop="initiator" />
          <el-table-column label="合同来源" align="center" key="contractSource" prop="contractSource"  />
          <el-table-column label="借款金额" align="center" key="applymoney" prop="creOrder.applymoney" v-if="columns[7].visible" :show-overflow-tooltip="true" />

</el-table>

  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
  
      <!-- 添加或修改用户配置对话框 -->
    <div class="orderFoodInfoTop pdfDom" id="pdfDom" ref="orderForm1">
      
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body align="center">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="22">
              <el-form-item label="信贷产品" prop="contractName">
                <el-input v-model="form.contractName" placeholder="信贷产品" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="合同编号" prop="contractNumber">
                <el-input v-model="form.contractNumber" placeholder="合同编号" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="借款方" prop="initiator">
                <el-input v-model="form.initiator" placeholder="甲方" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="贷款方" prop="contractSource">
                <el-input v-model="form.contractSource" placeholder="乙方" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="手机号" prop="initiatorPhone">
                <el-input v-model="form.initiatorPhone" placeholder="借款方手机号" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone" >
                <el-input  placeholder="12580" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="32">
              <el-form-item label="内容：" prop="address">
                <div class="orderFoodInfoTop pdfDom" id="pdfDom" ref="orderForm">
                <el-text width="max-width">第一条出借人向借款人提供借款资金{{form.creOrder.applymoney}}人民币。
                        
                         第二条本合同项下的借款期限为{{form.creOrder.loanTerm}}个月，自{{form.completionTime}}起共{{form.creOrder.loanTerm}}期。借款实际发放日与借款起始日不一
                        致的，借款起始日以借款实际发放日为准，借款期限随之顺延。
                          第三条借款指定用于，借款人不得挪作他用。
                        
                      第四条本合同项下借款利率为固定利率，借款月利率为{{form.creProduct.monthRate}} %。
                             第五条本合同项下借款本息采用等额本息方式归还: 
                    5.1本金到期，剩余本息一次性归还，利息按月支付，到期利随本清。每月利息{{form.creOrder.applymoney*form.creProduct.monthRate}}元
                     。如涉及到按日计算利息，日利率=月利率+30个点。付息日为每月的1日,还本日为借款到期日。
                     5.2等额本息还款法:即借款期限内每月以相等的额度偿还借款本息。每月还款额为人民币(大写金额):2000万元
                           ,还款日为每月1日。
                     第六条借款人应当将借款本金和利息通过转账方式支付到出借人名下的银行账户，按月支付，切记逾期。

                     <br>
                   <el-col :span="32">甲方：</el-col> 
                   <br>
                   <el-col :span="32">乙方：</el-col> 
                   <br>
                   <el-col :span="32">日期： 年   月  日</el-col> 
                     
                          </el-text> 
                        </div>
                        <br>
                          <el-text span="8" style="color:brown">
                            账户信息如下:{{creuser.bankCard}}
                           
</el-text>   

                <!-- <el-text span="8">
                 
                  开户名:123123  账号:123123    开户行:中国银行  银行卡号：
                </el-text>           -->
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="开户名" prop="contractName">
                <el-input v-model="form.initiator" placeholder="开户名" maxlength="30" />
              </el-form-item>
            </el-col>

       
            <el-col :span="10">
              <el-form-item label="卡号：" prop="contractSource" span="5">
                <el-input v-model="creuser.bankCard" placeholder="131414514598981" maxlength="30" />
              </el-form-item>
            </el-col>
            
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定签订协议</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <el-button type="primary" @click="getPdf">导出合同</el-button>
      </el-dialog>
  
    </div>
      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listContract, getContract, delUser, changeContractStatus, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/credit/creContract";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

  export default {

    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: { Treeselect },
    data() {
      return {
        // htmlTitle: "合同pdf",
        educationLevel:"",
        creditStanding: "",
        page: "",
        form: null,
        dialogVisible : false,
        title: "",
        // 遮罩层
        loading: true ,
         // 遮罩层
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        contractList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        page: undefined,

        // 日期范围
        dateRange: [],
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {
          creOrder: [],
          creProduct: [],
        },
       
       creuser: [],
       creuser: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          realName: undefined,
          phonenumber: undefined,
          userId:undefined,
          creContractId:undefined,
          status: undefined,
          deptId: undefined
        },
        // 列信息
        columns: [
          { key: 0, label: `编号`, visible: true },
          { key: 1, label: `用户id`, visible: true },
          { key: 2, label: `合同编号`, visible: true },
       
          { key: 3, label: `合同名称`, visible: true },
        
          { key: 4, label: `发起人`, visible: true },
          { key: 5, label: `发起人电话`, visible: true },
          { key: 6, label: `完成时间`, visible: true },
          { key: 7, label: `合同来源`, visible: true },
          { key: 8, label: `签署状态`, visible: true },
          
          { key: 9, label: `修改时间`, visible: true },
        
        ],
        // 表单校验
        rules: {
          userName: [
            { required: true, message: "用户名称不能为空", trigger: "blur" },
            { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
          ],
          nickName: [
            { required: true, message: "用户昵称不能为空", trigger: "blur" }
          ],
          password: [
            { required: true, message: "用户密码不能为空", trigger: "blur" },
            { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
          ],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          phonenumber: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        }
      };
    },
    // watch: {
    //   // 根据名称筛选部门树
    //   deptName(val) {
    //     this.$refs.tree.filter(val);
    //   }
    // },
    created() {
      this.getList();
      this.getConfigKey("sys.user.initPassword").then(response => {
        this.initPassword = response.msg;
      });
    },
    //监听
    watch: {
    form: function (newData, oldData) {
      console.log(oldData, newData);
  
      // this.form = newData.form;
      this.getList();
    }
  },
    methods: {
//下载pdf
      getPdf(){
// let _this= this
let myBox=this.$refs.orderForm;
html2canvas(myBox,{
  useCORS:true,
  allowTaint:true,
  dpi: 300,
  scale: 3,
}).then(function(canvas){
  let contentWidth=canvas.width
  let contentHeight=canvas.height
  let pageHeight=contentWidth
  let leftHeight=contentHeight
  let postion=0
  let imgWidth=560.28
  let imgHeight=592.28
  let pageData=canvas.toDataURL('image/jpeg',1.0)
  let PDF=new jsPDF('','pt','a4')
  if(leftHeight<pageHeight){
    PDF.addImage(pageData,'JPEG',20,20,imgWidth,imgHeight)
  }else{
    while(leftHeight>0){
      PDF.addImage(pageData,'JPEG',20,postion,imgWidth,imgHeight)
      leftHeight -=pageHeight
      postion -=841.89
      if(leftHeight>0){
        PDF.addImage()
      }
    }
  }
  PDF.save("合同"+'.pdf')
}).catch(err=>{
console.log(err)
        });
      },

       /** 查询还款表 */
       searchRefund(row) {
        dialogVisible = true;
        const userId = row.userId || this.ids;
        getContract(userId).then(response => {
          

          this.form = response.data;
            this.creuser=  response.creuser;
            
          
        });
      },


      
      /** 查询合同列表 */
      getList() {
        this.loading = true;
        listContract(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.contractList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
   
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.handleQuery();
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.realName + '"用户吗？').then(function() {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        // this.reset();
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
    



      // 表单重置
      reset() {
        this.form = {
          Id: undefined,
         userId: undefined,
         orderId: undefined,
         contractName: undefined,
         contractNumber: undefined,
         initiator: undefined,
         initiatorPhone: undefined,
         completionTime: undefined,
         contractSource: undefined,
         contractStatus:"0",
         monthRate: undefined,
          identityCard: undefined,
          bankCard: undefined,
          address: undefined,
          educationLevel: undefined,
          occupation: undefined,
          monthIncome: undefined,
          houseCertificate: undefined,
          creditStanding: undefined,
          loanDescription: undefined,
          emergencyPhone: undefined,
          creditStanding: undefined,
          updateTime: undefined,
          page: undefined,
          creOrder: [],
          crerefund: [],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleResetPwd":
            this.handleResetPwd(row);
            break;
          case "handleAuthRole":
            this.handleAuthRole(row);
            break;
          default:
            break;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        getContract().then(response => {
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.open = true;
          this.title = "添加用户";
          this.form.password = this.initPassword;
        });
        
      },

      /** 签署按钮操作 */
      handleUpdate(row) {
        this.reset();
        const orderId = row.orderId || this.ids;
        getContract(orderId).then(response => {
          

          this.form = response.data;
            this.creuser=  response.creuser;
          this.open = true;
          this.title = "借贷合同协议";
        });
      },

      /** 还款信息表操作按钮 */
      handleReturn(row) {
        this.reset();
        const userId = row.userId || this.ids;
        getContract(userId).then(response => {
          

          this.form = response.data;
            this.creuser=  response.creuser;
          this.open = true;
          this.title = "还款信息表";
        });
      },


      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
        }).then(({ value }) => {
            resetUserPwd(row.userId, value).then(response => {
              this.$modal.msgSuccess("修改成功，新密码是：" + value);
            });
          }).catch(() => {});
      },

      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.userId != undefined) {
              changeContractStatus(this.form).then(response => {
                this.$modal.msgSuccess("签订成功");
                this.open = false;
                this.getList();
              });
            } 
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.Id || this.ids;
        this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
          return delUser(userIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },


      /** 导出按钮操作 */
      handleExport() {
        this.download('credit/creUser/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('system/user/importTemplate', {
        }, `user_template_${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
  </script>